const log = require('../util/log'),
  config = require('../util/config'),
  chromeMng = require('../mng/chromeMng.20180824')

module.exports = (req, res) => {
  require('../util/service').handlePost(req, res, async (reqObj, resolve) => {
	const mongoMng = require('../mng/mongoMng')
    if (!mongoMng.db) {
      log('mongodb未连接')
      resolve({
        result: -1,
        msg: '系统错误'
      })
      return
    }
    if (!chromeMng.client) {
      log('chrome未连接')
      resolve({
        result: -1,
        msg: '系统错误'
      })
      return
    }
    if (!reqObj.keyword) {
      resolve({
        result: -1,
        msg: '缺少keyword'
      })
      return
    }
    getJdItem(reqObj).then(list => {
      var promises = []
      list.forEach(item => {
        promises.push(new Promise(resolve => {
          item.rate = Math.round(item.rate * config.returnRate * 100) / 100
          mongoMng.db.collection('item').find({
            link: item.link,
          }).toArray((err, result) => {
            if (err) {
              log(err);
              return;
            }
            if (result.length > 0 && result[0].advLink && result[0].advLink != -1) {
              item.advLink = result[0].advLink
            }
            resolve()
          })
        }))
      })
      Promise.all(promises).then(result => {
        resolve({
          list: list
        })
      }, result => {
        log(result)
        resolve({
          result: -1,
          msg: '系统错误'
        })
      })
    }, result => {
      log(result)
      resolve({
        result: -1,
        msg: result
      })
    })
  })
}

function getJdItem(obj) {
  if (chromeMng.busy) {
    if (Math.random() < 0.05) {
      return new Promise((resolve, reject) => {
        log('chrome繁忙')
        reject('系统繁忙')
      })
    }
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        getJdItem(obj).then(result => {
          resolve(result)
        }, reject => {
          resolve(reject)
        })
      }, 100)
    })
  }
  log('占用chrome')
  chromeMng.busy = true
  return new Promise((resolve, reject) => {
    chromeMng.getJdItems(obj).then(result => {
      log('获取京东商品成功，释放chrome')
      chromeMng.busy = false
      resolve(result)
    }, result => {
      log('获取京东商品失败，释放chrome', result)
      chromeMng.busy = false
      reject(result)
    })
  })
}
